package tbs.framework.sql.aop;

import cn.hutool.core.bean.copier.CopyOptions;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Lazy;
import tbs.framework.sql.mapper.impl.EntitySelectFetchMapper;
import tbs.framework.sql.query.IPage;
import tbs.framework.sql.query.IQuery;
import tbs.framework.utils.BeanUtil;
import tbs.framework.utils.CollUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * framework mapper aop, 用于处理查询结果集的aop
 */
@Aspect
public class FrameworkMapperAOP {

    @Pointcut("execution(* tbs.framework.sql.mapper.IFrameworkMapper.queryByQO(..))")
    public void queryPointCut() {

    }

    @Pointcut("execution(* tbs.framework.sql.mapper.IFrameworkMapper.countByQO(..))")
    public void countPointCut2() {
    }

    @Lazy
    @Resource
    EntitySelectFetchMapper entitySelectFetchMapper;

    @Around("queryPointCut()")
    Object query(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Map<String, Object> f = new HashMap<>();
        List<Map<String, Object>> list = entitySelectFetchMapper.queryByQO((IQuery)args[0], (IPage)args[1], f);
        if (CollUtils.isEmpty(list)) {
            return CollUtils.toReadOnlyList();
        }
        return list.stream().map(m -> {
            return BeanUtil.mapToBean(m, (Class<? extends Object>)args[2], true, CopyOptions.create());
        }).collect(Collectors.toList());

    }

    @Around("countPointCut2()")
    Object count(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        Map<String, Object> f = new HashMap<>();
        return entitySelectFetchMapper.countByQO((IQuery)args[0], f);
    }
}
